package com.example.yuv2image;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.view.View;

import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        new Thread(new Runnable() {
            @Override
            public void run() {
                releaseAsserts("input.yuv", getApplicationContext());
            }
        }).start();


    }

    @Override
    protected void onPostCreate(@Nullable Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

    }


    public void onTransferJPEG(View view) {
        NativeYUV2IMAGE yuv420p2jpeg = new NativeYUV2IMAGE();
        File yuvFile = new File(getExternalFilesDir(null), "input.yuv");
        File jpegFile = new File(getExternalFilesDir(null), "output.jpeg");
        yuv420p2jpeg.yuv2jpeg(yuvFile.getAbsolutePath(), jpegFile.getAbsolutePath(), 510, 510);
    }

    public void onTransferPNG(View view) {
        NativeYUV2IMAGE yuv2image = new NativeYUV2IMAGE();
        File yuvFile = new File(getExternalFilesDir(null), "input.yuv");
        File jpegFile = new File(getExternalFilesDir(null), "output.png");
        yuv2image.yuv2png(yuvFile.getAbsolutePath(), jpegFile.getAbsolutePath(), 510, 510);
    }




    /**
     * 释放Asserts目录下指定文件
     * @param fileName
     * @return
     */
    private String releaseAsserts(String fileName, Context context) {
        InputStream inputStream = null;
        FileOutputStream fos = null;
        try {
            Context appContext = context;
            if (appContext != null) {
                inputStream = appContext.getAssets().open(fileName);
                File targetFile = new File(appContext.getExternalFilesDir(null), fileName);
                fos = new FileOutputStream(targetFile);
                int length;
                byte[] buffer = new byte[8 * 1024];
                while ((length = inputStream.read(buffer)) != -1) {
                    fos.write(buffer, 0, length);
                    fos.flush();
                }
                return targetFile.getAbsolutePath();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ioClose(fos);
            ioClose(inputStream);
        }
        return null;
    }
    private void ioClose(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}